<?php

namespace app\api\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 会员组日志模型
 */
class Address extends Model
{

    use SoftDelete;
    // 表名
    protected $name = 'address';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [
    ];


    //添加/编辑地址
    public function add($param)
    {
        $id = isset($param['id']) ? $param['id'] : 0;

        $address_model = new Address();

        $data = [
            'user_id'=>$param['user_id'],
            'name'=>$param['name'],
            'mobile'=>$param['mobile'],
            'detail'=>$param['detail'],
            'shop_id'=>$param['shop_id'],
            'province_id'=>$param['province_id'],
            'province'=>$param['province'],
            'city_id'=>$param['city_id'],
            'city'=>$param['city'],
            'district_id'=>$param['district_id'],
            'district'=>$param['district'],
            'is_default'=>$param['is_default']
        ];

        if (empty($data['name'])){
            throw new Exception('请输入姓名');
        }
        if (empty($data['mobile'])){
            throw new Exception('请输入电话');
        }
        if (empty($data['province_id'])||empty($data['city_id'])||empty($data['district_id'])){
            throw new Exception('请选择所在地区');
        }
        if (empty($data['detail'])){
            throw new Exception('请输入详细地址');
        }
        if ($id){
            $address = Address::get([
                'id' =>$id,
                'user_id' => $data['user_id']
            ]);

            if (!$address){
                throw new Exception('地址不存在');
            }

            if ($data['is_default']==1){
                Address::where(['user_id' => $data['user_id']])->update(['is_default'=>0]);
            }

            $res = $address_model->save($data,['id'=>$id]);
        } else {
            if ($data['is_default']==1){
                Address::where(['user_id' => $data['user_id']])->update(['is_default'=>0]);
            }
            $res = $address_model->save($data);
        }

        return $res;
    }


}
